package org.xiaofeipapa.feimall.orderApi.service;

import org.springframework.beans.BeansException;
import org.springframework.cloud.bus.BusProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.xiaofeipapa.feimall.common.event.UserPayEvent;

import javax.annotation.Resource;

/**
 * 作者: 小肥爬爬
 * 简书: https://www.jianshu.com/u/db796a501972
 * gitee: https://gitee.com/xiaofeipapa
 * 邮箱: imyunshi@163.com
 * 您可以自由转载此博客文章, 恳请保留原链接, 谢谢!
 **/
@Component
public class OrderService implements ApplicationContextAware, ApplicationEventPublisherAware {

    ApplicationContext applicationContext;
    ApplicationEventPublisher applicationEventPublisher;

    @Resource
    BusProperties busProperties;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    // 模拟用户下单的方法
    public void createOrder(String userName){
        System.out.println("=========== 用户已经下单了. " + userName);

        // 触发事件
        UserPayEvent payEvent = new UserPayEvent(
                this,
                busProperties.getId(), "*:**", userName, true);

        // 这段代码适用于 event sender / consumer 都在同一工程
//        UserPayEvent payEvent = new UserPayEvent(
//                this,
//                applicationContext.getId(), null, userName, true);

        applicationEventPublisher.publishEvent(payEvent);
    }

}
